import React, { useState, useEffect } from 'react';
import { Table, Card, Typography, Button, Modal, Form, Input, Space, message } from 'antd';
import { SaveOutlined, DownloadOutlined } from '@ant-design/icons';
import { motion } from 'framer-motion';
import axios from 'axios';
import * as XLSX from 'xlsx';

const { Title } = Typography;

const FieldDictionary = ({ fields, onSaveFields, editingField, setEditingField, currentTable }) => {
  const [form] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [searchFieldText, setSearchFieldText] = useState('');

  useEffect(() => {
    if (editingField) {
      form.setFieldsValue(editingField);
      setIsModalVisible(true);
    }
  }, [editingField, form]);

  const showAddModal = () => {
    setEditingField(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    setEditingField(null);
  };

  const handleSubmit = async () => {
    try {
      if (!currentTable) {
        message.warning('请先选择数据表');
        return;
      }
      const values = await form.validateFields();
      let newFields;

      if (editingField) {
        newFields = fields.map(field => 
          field.englishField === editingField.englishField ? values : field
        );
      } else {
        // 检查字段是否已存在
        const exists = fields.some(field => field.englishField === values.englishField);
        if (exists) {
          message.error('该英文字段已存在');
          return;
        }
        newFields = [...fields, values];
      }

      // 保存到前端状态
      onSaveFields(newFields);

      // 保存到后端
      await axios.post(`/api/tables/${currentTable}/fields`, { fields: newFields });
      message.success(editingField ? '字段更新成功' : '字段添加成功');
      setIsModalVisible(false);
      setEditingField(null);
    } catch (error) {
      const errorMsg = error.response?.data?.error || '提交失败，请检查输入';
message.error(errorMsg);
    }
  };

  const handleManualSave = async () => {
  try {
    if (!currentTable) {
      message.warning('请先选择数据表');
      return;
    }
    await axios.post(`/api/tables/${currentTable}/fields`, { fields });
    message.success('字段数据已手动保存');
  } catch (error) {
    const errorMsg = error.response?.data?.error || '手动保存失败';
    message.error(errorMsg);
  }
};

const handleDelete = async (englishField) => {
    try {
      const newFields = fields.filter(field => field.englishField !== englishField);
      onSaveFields(newFields);
      await axios.post(`/api/tables/${currentTable}/fields`, { fields: newFields });
      message.success('字段删除成功');
    } catch (error) {
      const errorMsg = error.response?.data?.error || '删除失败';
message.error(errorMsg);
    }
  };

  // 初始加载字段数据
  useEffect(() => {
    const loadFields = async () => {
      try {
        const response = await axios.get(`/api/tables/${currentTable}/fields`);
        onSaveFields(response.data);
      } catch (error) {
        console.error('加载字段数据失败', error);
      }
    };

    if (!fields.length) {
      loadFields();
    }
  }, [fields.length, onSaveFields, currentTable]);
  const filteredFields = (fields || []).filter(field => 
  field && ((field?.englishField || '').toString().toLowerCase().includes((searchFieldText || '').toString().toLowerCase()) || 
   (field?.chineseName || '').toString().toLowerCase().includes((searchFieldText || '').toString().toLowerCase()))
);
const dataSource = filteredFields.map((field, index) => ({
    key: index,
    ...field
  }));

  // 定义表格列
  const columns = [
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" size="small" onClick={() => setEditingField(record)}>
            编辑
          </Button>
          <Button danger size="small" onClick={() => handleDelete(record.englishField)}>
            删除
          </Button>
        </Space>
      ),
    },
    {
      title: '英文字段',
      dataIndex: 'englishField',
      key: 'englishField',
      width: '40%',
      render: text => (
        <Typography.Text code style={{ fontSize: '14px' }}>
          {text}
        </Typography.Text>
      )
    },
    {
      title: '中文名称',
      dataIndex: 'chineseName',
      key: 'chineseName',
      width: '40%',
      render: text => (
        <Typography.Text strong style={{ fontSize: '14px' }}>
          {text}
        </Typography.Text>
      )
    }
  ];

  const handleExportExcel = () => {
    if (!fields.length) {
      message.warning('没有字段数据可导出');
      return;
    }
    
    const exportData = fields.map(field => ({
      '英文字段': field.englishField,
      '中文名称': field.chineseName
    }));
    
    const worksheet = XLSX.utils.json_to_sheet(exportData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, '字段映射');
    
    XLSX.writeFile(workbook, `${currentTable || '字段映射'}_字段导出.xlsx`);
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.5 }}
    >
      <Card
        title={<Title level={3}>字段管理</Title>}
        bordered
        style={{
          marginBottom: 20,
          background: 'linear-gradient(135deg, #f5f7fa 0%, #e4eaf5 100%)',
          borderRadius: 8
        }}
      >
        <Button 
          icon={<DownloadOutlined />} 
          onClick={handleExportExcel}
          style={{ marginBottom: 16 }}
        >
          导出Excel
        </Button>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Input
            placeholder="搜索字段..."
            value={searchFieldText}
            onChange={(e) => setSearchFieldText(e.target.value)}
            style={{ width: 200 }}
          />
          <Space>
            <Button type="primary" onClick={showAddModal}>+ 添加字段</Button>
            <Button type="default" onClick={handleManualSave} icon={<SaveOutlined />}>保存字段</Button>
          </Space>
        </div>
        <Table
          dataSource={dataSource}
          columns={columns}
          pagination={false}
          size="middle"
          showHeader
          rowHover
          style={{ background: '#fff', borderRadius: 4 }}
          locale={{ emptyText: '暂无字段数据，请点击"添加字段"按钮创建' }}
        />

        <Modal
          title={editingField ? '编辑字段' : '添加字段'}
          visible={isModalVisible}
          onCancel={handleCancel}
          footer={[
            <Button key="cancel" onClick={handleCancel}>取消</Button>,
            <Button key="submit" type="primary" onClick={handleSubmit}>保存</Button>,
          ]}
        >
          <Form form={form} layout="vertical" name="field_form">
            <Form.Item
              name="englishField"
              label="英文字段"
              rules={[{ required: true, message: '请输入英文字段名' }]}
              disabled={!!editingField}
            >
              <Input placeholder="例如: GJAHR" />
            </Form.Item>
            <Form.Item
              name="chineseName"
              label="中文名称"
              rules={[{ required: true, message: '请输入中文名称' }]}
            >
              <Input placeholder="例如: 年份" />
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </motion.div>
  );
};

export default FieldDictionary;